#pragma once
#include<iostream>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<stdio.h>
#include<string>
#include<cstring>
#include<unistd.h>


#define MAX_CONNECT 5
#define BUFFER_SIZE 1024

using std::cout;
using std::endl;

class Socket
{
public:
    Socket(int _fd=-1):fd(_fd)
    {};

    void _socket(){
        fd=socket(AF_INET,SOCK_STREAM,0);
        if(fd==-1){
            cout<<strerror(errno)<<endl;
            perror("creat scoket error!");
            //MassageLog(ERROR,"creat scoket error!",strerror(errno),__FILE__);
        }
    }
    void Bind(const std::string& Ip,uint16_t Port){
        sockaddr_in addr;
        addr.sin_family=AF_INET;
        addr.sin_addr.s_addr=inet_addr(Ip.c_str());
        addr.sin_port=htons(Port);
        int ret=bind(fd,(sockaddr*)&addr,sizeof(addr));
        if(ret==-1){
            cout<<strerror(errno)<<endl;
            perror("bind error!");
        }
    }
    void Listen(){
        int ret=listen(fd,MAX_CONNECT);
        if(ret==-1){
            cout<<strerror(errno)<<endl;
            perror("lsiten scoket error!");
        }
    }
    void Close(){
        int ret=close(fd);
        if(ret==-1){
            cout<<strerror(errno)<<endl;
            perror("close error!");
        }
    }
    int Connect(const std::string& Ip,uint16_t Port){
        sockaddr_in addr;
        addr.sin_family=AF_INET;
        addr.sin_addr.s_addr=inet_addr(Ip.c_str());
        addr.sin_port=htons(Port);
        int ret=connect(fd,(sockaddr*)&addr,sizeof(addr));
        if(ret==-1){
            cout<<strerror(errno)<<endl;
            perror("connect error!");
        }
        return ret;
    }
    int Accept(sockaddr* backAddr,socklen_t& len){
        int ret=accept(fd,backAddr,&len);
        if(ret==-1){
            cout<<strerror(errno)<<endl;
            perror("accept error!");
        }
        return ret;
    }
    ssize_t Recv(std::string& recvMassage){
        char buffer[BUFFER_SIZE];
        ssize_t receiveSize=recv(fd,buffer,BUFFER_SIZE-1,0);
        if(receiveSize==-1){
            cout<<strerror(errno)<<endl;
            perror("receive error!");
        }
        else if (receiveSize==0){

        }
        else{

        }
        buffer[receiveSize]=0;
        recvMassage.assign(buffer);
        return receiveSize;
    }
    ssize_t Send(const std::string& sendMassage){
        ssize_t sendSize=send(fd,sendMassage.c_str(),sendMassage.size(),0);
        if(sendSize==-1){
            cout<<strerror(errno)<<endl;
            perror("send error!");
        }
        else if(sendSize==0){

        }
        else{

        }
        return sendSize;
    }
    bool isVaild(){
        return fd>=0;
    }
    int Fd(){
        return fd;
    }
protected:
    int fd;
};